package com.nbgroup.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nbgroup.mapper.ActivityMapper;
import com.nbgroup.pojo.Activity;
import com.nbgroup.pojo.common.PageBean;
import com.nbgroup.pojo.common.PageResult;
import com.nbgroup.pojo.dto.PageActivityDTO;
import com.nbgroup.service.ActivityService;
import com.nbgroup.util.RandomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class ActivityServiceImpl implements ActivityService {
    private final ActivityMapper activityMapper;
    private final RandomUtil randomUtil;
    @Override
    public PageBean activityPageQuery(PageActivityDTO pageActivityDTO) {
        pageActivityDTO.check();
        PageHelper.startPage(pageActivityDTO.getPageNum(),pageActivityDTO.getPageSize());
        Page<Activity> activities =activityMapper.activityPageQuery(pageActivityDTO);
        PageBean pageBean = new PageBean();
        pageBean.setTotal(activities.getTotal());
        pageBean.setRows(activities.getResult());
        return pageBean;
    }

    @Override
    public void addActivity(Activity activity) {
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        ifName(activity);
        //会随机生成一个8位的编码
        String randomNumber = randomUtil.getRandomNumber();
        activity.setCode(randomNumber);
        activityMapper.addActivity(activity);
    }

    @Override
    public void updateActivity(Activity activity) {
        activity.setUpdateTime(LocalDateTime.now());
        Activity activity1 = activityMapper.queryById(activity.getId());
        if (!activity.getName().equals(activity1.getName())){
            ifName(activity);
        }
        activityMapper.updateActivity(activity);
    }

    @Override
    public Activity queryById(Long id) {
       Activity activity =activityMapper.queryById(id);
        return activity;
    }

    @Override
    public void deleteActivity(Long id) {
        activityMapper.deleteActivity(id);
    }

    public void ifName(Activity activity){
        List<Activity> activities = activityMapper.queryAllActivity();
        for (Activity activity1 : activities) {
            //名字不可重复
            if (activity.getName().equals(activity1.getName())){
                throw new RuntimeException();
            }
        }
    }
}
